<template>
  <div class="min-h-screen flex items-center justify-center px-4">
    <div class="w-full max-w-md card-rect p-8 text-white/90">
      <h1 class="text-3xl font-extrabold text-center mb-8 tracking-wide">登录</h1>

      <!-- 短信登录 -->
      <div v-if="tab==='sms'" class="space-y-6">
        <div class="flex gap-2">
          <div class="w-24">
            <select class="select-rect w-full">
              <option>+86</option>
            </select>
          </div>
          <input v-model.trim="phone" maxlength="11" class="input-rect flex-1" placeholder="输入手机号" autocomplete="tel" type="tel" inputmode="numeric" @input="digitsOnly('phone')" />
        </div>

        <div class="grid grid-cols-3 gap-2">
          <input v-model.trim="code" maxlength="6" class="input-rect col-span-2" placeholder="输入验证码" type="text" inputmode="numeric" autocomplete="one-time-code" @input="digitsOnly('code')" />
          <button type="button" class="btn-dark w-full h-11" :disabled="countdown>0 || !/^\d{11}$/.test(phone)" @click="sendCode">{{ countdown>0 ? `${countdown}s` : '获取验证码' }}</button>
        </div>

        <label class="flex items-center gap-2 text-sm text-white/60 select-none">
          <input type="checkbox" class="accent-emerald-500" />
          我已阅读并同意 <a href="#" class="text-white hover:underline">服务条款</a> 和 <a href="#" class="text-white hover:underline">隐私政策</a>
        </label>

        <button class="btn-solid w-full h-11" :disabled="!/^\d{11}$/.test(phone) || (code?.length||0) < 6" @click="onSMSLogin">登录</button>
        
        <!-- 新增：注册按钮（与登录按钮风格一致，放置在其下方） -->
        <button type="button" class="btn-solid w-full h-11" @click="router.push('/register')">注册</button>

        <div class="border-t border-white/10" />
        <button type="button" class="btn-dark w-full h-11" @click="tab='password'">账号密码登录</button>
      </div>

      <!-- 账号密码登录 -->
      <form v-else class="space-y-6" @submit.prevent="onPasswordLogin">
        <input v-model.trim="account" class="input-rect w-full" placeholder="输入手机号或账号" autocomplete="username" />
        <input v-model="password" type="password" class="input-rect w-full" placeholder="输入密码（至少6位）" autocomplete="current-password" />
        <button class="btn-solid w-full h-11" :disabled="!account || (password?.length||0)<6">登录</button>
        
        <!-- 新增：注册按钮（与登录按钮风格一致，放置在其下方） -->
        <button type="button" class="btn-solid w-full h-11" @click="router.push('/register')">注册</button>

        <div class="border-t border-white/10" />
        <button type="button" class="btn-dark w-full h-11" @click="tab='sms'">短信验证码登录</button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import {login as loginApi} from "@/api/loginApi.js";
import toast from "@/composables/toast.js";

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()

// 默认短信登录，如需默认账号密码登录，将 'sms' 改为 'password'
const tab = ref('sms')

const account = ref('')
const password = ref('')

const phone = ref('')
const code = ref('')
const countdown = ref(0)
let timer

async function onPasswordLogin(){
  if (!account.value || (password.value?.length || 0) < 6) {
    window.alert('请输入正确的账号和至少6位密码')
    return
  }
  try {
    // 使用 Pinia 的后端登录能力：内部会请求后端、设置 token 到 sessionStorage，并写入 auth.user
    await auth.login({ account: account.value, password: password.value })

    toast.success('登录成功')

    // 使用 ?redirect=xxx 回跳；无则回首页
    const redirect = route.query?.redirect
    const target = typeof redirect === 'string' && redirect ? redirect : '/'
    await router.push(target)
  } catch (e) {
    toast.error(e?.message || '登录失败')
  }
}
function clearTimer(){ if(timer){ clearInterval(timer); timer = null } }

function startCountdown(sec){
  clearTimer()
  countdown.value = sec
  if(sec>0){
    timer = setInterval(()=>{
      countdown.value--
      if(countdown.value<=0){ clearTimer(); countdown.value = 0 }
    }, 1000)
  }
}

function onSMSLogin(){
  if(!/^\d{11}$/.test(phone.value) || (code.value?.length||0) < 6){
    window.alert('请输入正确的手机号和验证码')
    return
  }
  // TODO: 接入后端短信登录；先提示，避免调用未实现方法导致报错
  window.alert('短信登录暂未开通')
}

function sendCode(){
  if(!/^\d{11}$/.test(phone.value)){
    window.alert('请输入正确的手机号')
    return
  }
  // TODO: 调用后端发码接口。先模拟成功并开始倒计时
  localStorage.setItem('sms_last_'+phone.value, String(Date.now()))
  startCountdown(60)
}

function digitsOnly(field){
  if(field==='phone') phone.value = (phone.value||'').replace(/\D+/g, '').slice(0,11)
  if(field==='code') code.value = (code.value||'').replace(/\D+/g, '').slice(0,6)
}

watch(phone, (val)=>{
  clearTimer()
  if(/^\d{11}$/.test(val)){
    const last = Number(localStorage.getItem('sms_last_'+val) || 0)
    const elapsed = Date.now() - last
    const remain = Math.ceil((60_000 - elapsed)/1000)
    if(remain>0 && remain<=60){ startCountdown(remain) }
    else { countdown.value = 0 }
  } else {
    countdown.value = 0
  }
}, { immediate: false })

onBeforeUnmount(()=>{ clearTimer() })
</script>